'use strict'

import { app, protocol, BrowserWindow, ipcMain, Menu, dialog, nativeTheme, Tray, shell, Notification } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
// import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer' // Temporarily commented out
import nodePath from 'path' // Renamed to avoid conflict with store.path
import Store from 'electron-store'
import fs from 'fs-extra' // For file operations
import dbModule from './db' // 导入SQLite数据库模块

// Attempt to set AppUserModelID early
if (process.platform === 'win32') { // AppUserModelID is primarily a Windows concept
  app.setAppUserModelId("待办待阅");
}

app.disableHardwareAcceleration();

// --- Path Configuration Store ---
// This store saves the preferred path for the main application data.
const pathStore = new Store({
  name: 'path-config', // Results in path-config.json in electron-store's default dir
  defaults: {
    customDataPath: null // null means use default app data path
  }
});
console.log('[background.js] Path configuration store initialized. Path:', pathStore.path);
console.log('[background.js] Initial customDataPath from pathStore:', pathStore.get('customDataPath'));

// 初始化SQLite数据库
const preferredDataPath = pathStore.get('customDataPath');
let dbPath;

// 创建store实例（简化版），仅用于获取sqlitePath设置
const tempStore = new Store({
  name: 'config',
  ...(preferredDataPath ? { cwd: preferredDataPath } : {})
});
const sqlitePathSetting = tempStore.get('settings.sqlitePath');
console.log('[background.js] tempStore路径:', tempStore.path);
console.log('[background.js] 从config.json中读取SQLite路径设置:', sqlitePathSetting);

if (sqlitePathSetting) {
  // 如果配置文件中指定了SQLite数据库路径，优先使用
  try {
    const sqliteDir = nodePath.dirname(sqlitePathSetting);
    fs.ensureDirSync(sqliteDir);
    dbPath = sqlitePathSetting;
    console.log(`[background.js] 使用config.json中配置的数据库路径: ${dbPath}`);
  } catch (err) {
    console.error(`[background.js] 无法使用配置的数据库路径 ${sqlitePathSetting}:`, err);
    // 回退到默认数据库路径
    if (preferredDataPath && typeof preferredDataPath === 'string') {
      dbPath = nodePath.join(preferredDataPath, 'todolist.db');
    } else {
      dbPath = nodePath.join(app.getPath('userData'), 'todolist.db');
    }
    console.log(`[background.js] 回退到默认数据库路径: ${dbPath}`);
  }
} else if (preferredDataPath && typeof preferredDataPath === 'string') {
  try {
    fs.ensureDirSync(preferredDataPath);
    dbPath = nodePath.join(preferredDataPath, 'todolist.db');
    console.log(`[background.js] 设置数据库路径为自定义路径: ${dbPath}`);
  } catch (err) {
    console.error(`[background.js] 无法使用自定义路径 ${preferredDataPath}:`, err);
    dbPath = nodePath.join(app.getPath('userData'), 'todolist.db');
    console.log(`[background.js] 回退到默认数据库路径: ${dbPath}`);
  }
} else {
  dbPath = nodePath.join(app.getPath('userData'), 'todolist.db');
  console.log(`[background.js] 使用默认数据库路径: ${dbPath}`);
}

// 尝试访问并写入文件系统,确认路径可写
try {
  const testFilePath = nodePath.join(nodePath.dirname(dbPath), 'test_write_access.tmp');
  fs.writeFileSync(testFilePath, 'test');
  fs.unlinkSync(testFilePath);
  console.log(`[background.js] 数据库目录可写: ${nodePath.dirname(dbPath)}`);
} catch (fsError) {
  console.error(`[background.js] 警告: 数据库目录不可写:`, fsError);
  // 尝试使用临时目录
  dbPath = nodePath.join(app.getPath('temp'), 'todolist.db');
  console.log(`[background.js] 尝试使用临时目录作为备选: ${dbPath}`);
}

// 初始化数据库
// console.log(`[background.js] 开始初始化数据库: ${dbPath}`); // Moved to app.on('ready')
// const dbInitialized = dbModule.initDatabase(dbPath); // Moved to app.on('ready')
// console.log(`[background.js] SQLite数据库初始化${dbInitialized ? '成功' : '失败'}`); // Moved to app.on('ready')

// if (!dbInitialized) { // Logic moved to app.on('ready')
//   console.log('[background.js] 由于SQLite数据库初始化失败，将使用electron-store进行数据存储');
// }
let dbInitialized = false; // Will be set in app.on('ready')

// Initialize electron-store
// 只保留配置相关schema，移除待办事项数据结构
const schema = {
  settings: {
    type: 'object',
    properties: {
      theme: { type: 'string', enum: ['light', 'dark', 'system'], default: 'dark' },
      miniMode: { type: 'boolean', default: false },
      alwaysOnTop: { type: 'boolean', default: false },
      closePreference: { type: 'string', enum: ['ask', 'tray', 'close'], default: 'ask' },
      dontAskAgainOnClose: { type: 'boolean', default: false },
      showCloseDialog: { type: 'boolean', default: true },
      closeDialogDefaultAction: { type: 'string', default: 'tray' },
      launchOnStartup: { type: 'boolean', default: false },
      sqlitePath: { type: ['string', 'null'], default: null } // 允许null值或字符串类型
    }
  }
};

// 配置文件检查和初始化部分
// 确定配置文件路径
let configFilePath = '';
if (preferredDataPath && typeof preferredDataPath === 'string') {
  try {
    // Ensure the directory exists, or create it.
    // electron-store typically handles this, but good to be sure.
    fs.ensureDirSync(preferredDataPath);
    configFilePath = nodePath.join(preferredDataPath, 'config.json');
    console.log(`[background.js] 配置文件将使用自定义路径: ${configFilePath}`);
  } catch (err) {
    console.error(`[background.js] 确保自定义数据目录存在时出错 ${preferredDataPath}. 回退到默认路径。错误:`, err);
    // Fallback to default if directory can't be ensured (e.g. permissions)
    configFilePath = nodePath.join(app.getPath('userData'), 'config.json');
  }
} else {
  console.log('[background.js] 使用默认配置文件路径');
  configFilePath = nodePath.join(app.getPath('userData'), 'config.json');
}

// 检查配置文件是否已存在
const configFileExists = fs.existsSync(configFilePath);
console.log(`[background.js] 检查配置文件是否存在: ${configFilePath}, 结果: ${configFileExists}`);

// 定义初始Store选项
let storeOptions = {
  schema: { ...schema },
  name: 'config' // 确保文件名为config.json
};

// 如果自定义目录路径存在，设置cwd选项
if (preferredDataPath && typeof preferredDataPath === 'string') {
  storeOptions.cwd = preferredDataPath;
}

// 如果配置文件已存在，不进行初始化，只使用现有配置
if (configFileExists) {
  console.log('[background.js] 配置文件已存在，保留现有配置，不进行初始化');
  
  try {
    // 尝试读取现有配置文件
    const existingConfig = JSON.parse(fs.readFileSync(configFilePath, 'utf8'));
    console.log('[background.js] 成功读取现有配置文件');
    
    // 删除schema中的所有默认值，以确保不会覆盖现有配置
    if (storeOptions.schema && storeOptions.schema.settings && storeOptions.schema.settings.properties) {
      Object.keys(storeOptions.schema.settings.properties).forEach(key => {
        if (storeOptions.schema.settings.properties[key].hasOwnProperty('default')) {
          delete storeOptions.schema.settings.properties[key].default;
        }
      });
    }
    
    // 如果存在settings.default属性，也将其删除
    if (storeOptions.schema && storeOptions.schema.settings && storeOptions.schema.settings.default) {
      delete storeOptions.schema.settings.default;
    }
    
    console.log('[background.js] 已移除schema中的默认值，以避免覆盖现有配置');
  } catch (readError) {
    console.error('[background.js] 读取现有配置文件失败:', readError);
    // 出错时仍然继续，创建store实例可能会覆盖坏的配置文件
  }
} else {
  console.log('[background.js] 配置文件不存在，将使用默认值初始化');
  // 如果是新配置文件，保留默认值
}

const store = new Store(storeOptions);
console.log('[background.js] 配置存储初始化完成，路径:', store.path);

// Watch for changes in settings, specifically for launchOnStartup
store.onDidChange('settings', (newValue, oldValue) => {
  if (newValue && oldValue && newValue.launchOnStartup !== oldValue.launchOnStartup) {
    console.log(`[background.js] launchOnStartup changed from ${oldValue.launchOnStartup} to ${newValue.launchOnStartup}. Applying setting.`);
    applyLoginItemSettings(newValue.launchOnStartup);
  }
});

// Function to apply login item settings (ensure it's defined before app.on('ready'))
function applyLoginItemSettings(shouldLaunchOnStartup) {
  if (app.isPackaged) { // Only manage this for packaged app
    const appPath = app.getPath('exe');
    const settings = {
      openAtLogin: shouldLaunchOnStartup,
      path: appPath, // On Windows, path must be set explicitly.
    };
    
    // 只有在设置开机自启动时才添加--launch-in-tray参数
    if (shouldLaunchOnStartup) {
      settings.args = ['--launch-in-tray'];
    }
    
    console.log(`[background.js] Setting login item. Settings: ${JSON.stringify(settings)}`);
    app.setLoginItemSettings(settings);
  } else {
    console.log('[background.js] Development mode: Login item settings not applied.');
  }
}

// store.clear(); // DEBUG: Clear store for testing initial state
// console.log('[background.js] Initial store content:', store.store);

// Store.initRenderer(); // Not needed and won't work as expected with contextIsolation:true and nodeIntegration:false. IPC is the way.

const isDevelopment = process.env.NODE_ENV !== 'production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

let mainWindow = null;
let forceQuit = false;
let tray = null; // Variable to hold the Tray instance

// Extracted function to handle the actual mode switch logic
function performToggleMiniMode(isMiniBoolean) {
  console.log(`[background.js] performToggleMiniMode called. Target isMini: ${isMiniBoolean}, Type: ${typeof isMiniBoolean}`);
  if (mainWindow && !mainWindow.isDestroyed()) {
    if (typeof isMiniBoolean !== 'boolean') {
      console.error('[background.js] performToggleMiniMode: isMiniBoolean was not a boolean! Defaulting to false (normal mode).');
      isMiniBoolean = false;
    }

    // Always unmaximize before attempting to resize to a smaller fixed size or a specific normal size
    if (mainWindow.isMaximized()) {
        mainWindow.unmaximize();
    }
    
    mainWindow.setResizable(true); // Ensure resizable before size changes

    if (isMiniBoolean) {
      console.log('[background.js] Setting to Mini Mode visuals via performToggleMiniMode.');
      mainWindow.setMinimumSize(300, 400); 
      console.log('[background.js] mainWindow.setMinimumSize(300, 400) CALLED for mini mode.');
      mainWindow.setSize(300, 400, true); // Animate flag can be true or false
      console.log('[background.js] mainWindow.setSize(300, 400) CALLED.'); 
      // mainWindow.setResizable(false); // Optional: make mini mode not resizable after setting size
      // Note: We do not set alwaysOnTop here when entering mini mode.
      // That is handled by 'toggle-always-on-top' IPC from MiniModeView.
    } else {
      console.log('[background.js] Setting to Normal Mode visuals via performToggleMiniMode (exiting mini mode).');
      const targetWidth = 1500; // Default normal size
      const targetHeight = 800; // Default normal size

      mainWindow.setMinimumSize(800, 600);
      console.log('[background.js] mainWindow.setMinimumSize(800, 600) CALLED for normal mode.');
      mainWindow.setSize(targetWidth, targetHeight, true); // Animate flag
      console.log(`[background.js] mainWindow.setSize(${targetWidth}, ${targetHeight}) CALLED.`); 
      // mainWindow.setResizable(true); // Ensure it stays true for normal mode (already set above)
      
      // CRITICAL: When switching back to normal mode, ensure always-on-top is disabled.
      mainWindow.setAlwaysOnTop(false);
      console.log('[background.js] Exited mini mode. Window always-on-top explicitly set to false.');
    }

    const newSize = mainWindow.getSize();
    console.log(`[background.js] Size AFTER setSize for ${isMiniBoolean ? 'mini' : 'normal'} mode: ${newSize[0]}x${newSize[1]}`);

    // 保存miniMode设置到electron-store
    console.log(`[background.js] 保存miniMode设置到electron-store: ${isMiniBoolean}`);
    const currentSettings = store.get('settings', { theme: 'dark', miniMode: false }); // Ensure default if settings don't exist
    const newSettings = { ...currentSettings, miniMode: isMiniBoolean };
    store.set('settings', newSettings); // Save updated settings object

    // Send back to renderer so UI can update (e.g. Vuex state, button appearance)
    if (!mainWindow.isDestroyed()) { // Check again before sending
        console.log(`[background.js] Sending 'toggle-mini-mode' to renderer with isMini: ${isMiniBoolean}`); // 修改日志以表明发送已启用
        mainWindow.webContents.send('toggle-mini-mode', isMiniBoolean); // <<--- RE-ENABLING THIS LINE
    }

  } else {
    console.warn('[background.js] performToggleMiniMode: mainWindow is not available or destroyed.');
  }
}

// Constants for mini mode dimensions
const MINI_MODE_EXPANDED_HEIGHT = 400; // Standard height when mini mode is expanded
const MINI_MODE_COLLAPSED_HEIGHT = 50; // Height when mini mode header is collapsed (adjust as needed)

ipcMain.on('toggle-mini-expand', (event, isExpanded) => {
  // 从electron-store获取miniMode设置
  let isMiniMode = store.get('settings.miniMode', false);
  console.log(`[background.js] 从electron-store获取miniMode设置: ${isMiniMode}`);
  
  if (mainWindow && !mainWindow.isDestroyed() && isMiniMode) {
    console.log(`[background.js] Received 'toggle-mini-expand' from renderer. isExpanded: ${isExpanded}`);
    const currentSize = mainWindow.getSize();
    const currentWidth = currentSize[0]; // Mini mode should maintain its width
    const newHeight = isExpanded ? MINI_MODE_EXPANDED_HEIGHT : MINI_MODE_COLLAPSED_HEIGHT;
    
    mainWindow.setMinimumSize(currentWidth, newHeight); 
    mainWindow.setSize(currentWidth, newHeight, true); // Animate height change
    console.log(`[background.js] Mini mode window resized. Width: ${currentWidth}, New Height: ${newHeight}`);
  } else {
    console.warn(`[background.js] 'toggle-mini-expand' received but not in mini mode or window not available.`);
  }
});

// IPC handler for toggling always-on-top
ipcMain.on('toggle-always-on-top', (event, newState) => {
  if (mainWindow && !mainWindow.isDestroyed()) {
    if (typeof newState === 'boolean') {
      mainWindow.setAlwaysOnTop(newState);
      console.log(`[background.js] Window always-on-top state set to: ${newState}`);
    } else {
      console.warn(`[background.js] 'toggle-always-on-top' received invalid state: ${newState}. Expected boolean.`);
    }
  } else {
    console.warn("[background.js] 'toggle-always-on-top' received but mainWindow is not available.");
  }
});

// New IPC Handlers for Store Path
ipcMain.handle('get-store-path', () => {
  if (store && store.path) {
    return store.path;
  }
  console.error('[background.js] Store instance or store.path is not available for get-store-path.');
  return null;
});

// 新增：获取SQLite数据库文件路径
ipcMain.handle('get-sqlite-db-path', () => {
  if (dbModule && dbPath) {
    return dbPath;
  }
  console.error('[background.js] dbModule或dbPath不可用');
  return null;
});

// Changed from ipcMain.handle to ipcMain.on to match ipcRenderer.send from preload.js
ipcMain.on('open-store-folder', (event) => { 
  if (store && store.path) {
    try {
      shell.showItemInFolder(store.path);
    } catch (error) {
      console.error('[background.js] Failed to open store folder:', error);
    }
  } else {
    console.error('[background.js] Store instance or store.path is not available for open-store-folder.');
  }
});

// 新增：打开SQLite数据库所在文件夹
ipcMain.on('open-sqlite-db-folder', (event) => {
  if (dbPath) {
    try {
      shell.showItemInFolder(dbPath);
    } catch (error) {
      console.error('[background.js] 打开SQLite数据库文件夹失败:', error);
    }
  } else {
    console.error('[background.js] dbPath不可用');
  }
});

async function createWindow() {
  console.log('[background.js] createWindow called.');
  console.log(`[background.js] process.env.ELECTRON_NODE_INTEGRATION: ${process.env.ELECTRON_NODE_INTEGRATION}`);
  const resolvedNodeIntegration = process.env.ELECTRON_NODE_INTEGRATION === 'true' || process.env.ELECTRON_NODE_INTEGRATION === true;
  const resolvedContextIsolation = !(process.env.ELECTRON_NODE_INTEGRATION === 'true' || process.env.ELECTRON_NODE_INTEGRATION === true);
  
  console.log(`[background.js] Calculated nodeIntegration for BrowserWindow: ${resolvedNodeIntegration}`);
  console.log(`[background.js] Calculated contextIsolation for BrowserWindow: ${resolvedContextIsolation}`);

  // 获取当前主题设置
  const currentTheme = store.get('settings.theme', 'dark');
  console.log(`[background.js] 从config.json获取主题设置: ${currentTheme}`);

  // 设置应用图标路径
  const iconPath = isDevelopment 
    ? nodePath.join(process.cwd(), 'public', 'app-icon.ico')
    : nodePath.join(process.resourcesPath, 'app-icon.ico');
  console.log(`[background.js] 设置应用图标路径: ${iconPath}`);

  mainWindow = new BrowserWindow({
    show: false,
    width: 1600,
    height: 1000,
    minWidth: 800,
    minHeight: 600,
    icon: iconPath, // 添加任务栏图标设置
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: nodePath.join(__dirname, 'preload.js'),
      devTools: isDevelopment
    },
    titleBarStyle: 'hidden',
    frame: false,
  })

  // NEW: Handle minimize event to hide window to tray
  mainWindow.on('minimize', (event) => {
    event.preventDefault(); // Prevent normal minimize
    mainWindow.hide();      // Hide the window
  });

  // Listener for maximize/unmaximize events to send to renderer
  mainWindow.on('maximize', () => {
    if (mainWindow && mainWindow.webContents) {
    mainWindow.webContents.send('window-maximized');
    }
  });
  mainWindow.on('unmaximize', () => {
    if (mainWindow && mainWindow.webContents) {
    mainWindow.webContents.send('window-unmaximized');
    }
  });

  /* Temporarily comment out Vue Devtools installation to check if it causes the loading delay
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS);
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString());
    }
  }
  */

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    await mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST && mainWindow && mainWindow.webContents) mainWindow.webContents.openDevTools()
  } else {
    createProtocol('app')
    mainWindow.loadURL('app://./index.html')
  }

  // 在窗口内容加载完成后发送主题设置
  mainWindow.webContents.on('did-finish-load', () => {
    // 再次获取主题设置，确保是最新的
    const themeToApply = store.get('settings.theme', 'dark');
    console.log(`[background.js] 窗口加载完成，发送主题设置到渲染进程: ${themeToApply}`);
    mainWindow.webContents.send('apply-theme', themeToApply);
  });

  // Check for the launch-in-tray argument
  const launchInTray = process.argv.includes('--launch-in-tray');
  // 检查是否应该在重启后显示窗口
  const showOnRestart = process.argv.includes('--show-on-restart');
  console.log(`[background.js] Checking for --launch-in-tray. Found: ${launchInTray}`);
  console.log(`[background.js] Checking for --show-on-restart. Found: ${showOnRestart}`);
  console.log('[background.js] process.argv:', process.argv);

  // 检查electron-store中是否有重启显示窗口的标志
  const restartShowWindow = store.get('restart_show_window', false);
  if (restartShowWindow) {
    console.log('[background.js] 检测到restart_show_window标志为true，将强制显示窗口');
    // 使用后删除此标志
    store.delete('restart_show_window');
  }

  // 检查是否是开机自启动
  const isLaunchFromStartup = launchInTray && app.isPackaged;
  console.log(`[background.js] 是否是开机自启动: ${isLaunchFromStartup}`);

  // 只有在开机自启动时才隐藏窗口，其他情况都显示窗口
  if (isLaunchFromStartup && !showOnRestart && !restartShowWindow) {
    console.log('[background.js] 开机自启动检测到，窗口将初始隐藏');
    // 窗口已经创建时设置了show: false，无需额外隐藏
  } else {
    // 非开机自启动或者需要显示窗口的情况
    mainWindow.once('ready-to-show', () => {
        console.log('[background.js] Window ready-to-show, showing main window.');
        mainWindow.show();
        mainWindow.focus(); // 确保窗口获得焦点
    });
  }

  // mainWindow.on('closed', () => {
  //   mainWindow = null
  // })

  // Handle window close requests
  mainWindow.on('close', (event) => {
    console.log('[background.js] mainWindow close event triggered.');
    
    // 直接从electron-store获取设置
    const currentSettings = store.get('settings', {});
    const userShowCloseDialog = currentSettings.showCloseDialog !== false; // 默认为true
    const userCloseDialogDefaultAction = currentSettings.closeDialogDefaultAction || 'tray';
    
    console.log(`[background.js] 从electron-store获取关闭设置: showCloseDialog=${userShowCloseDialog}, closeDialogDefaultAction=${userCloseDialogDefaultAction}`);

    // If forceQuit is true, we should bypass all dialogs and preferences and just quit.
    if (forceQuit) {
      console.log('[background.js] forceQuit is true, allowing app to quit directly.');
      // Do not call event.preventDefault() here, let the app quit normally.
      // app.quit() might have already been called, or will be by the system.
    return;
  }

    if (userShowCloseDialog) {
      console.log('[background.js] showCloseDialog is true, preventing default and sending request for custom confirmation.');
      event.preventDefault();
      if (mainWindow && mainWindow.webContents) {
        mainWindow.webContents.send('request-custom-close-confirmation');
      } else {
        console.warn('[background.js] mainWindow or webContents not available to send request-custom-close-confirmation. Forcing quit.');
        forceQuit = true; // Set forceQuit before direct quit
        app.quit(); // Fallback if window is somehow gone
      }
    } else {
      console.log('[background.js] showCloseDialog is false, proceeding with default action.');
      event.preventDefault(); // Still prevent default to handle it manually
      if (userCloseDialogDefaultAction === 'tray') {
        console.log('[background.js] Default action is to minimize to tray.');
        if (mainWindow) {
          mainWindow.hide();
        }
      } else if (userCloseDialogDefaultAction === 'close') {
        console.log('[background.js] Default action is to close the app. Setting forceQuit and calling app.quit().');
        forceQuit = true; // Explicitly set forceQuit to true
        app.quit();
      } else {
        // Fallback, should not happen if settings are validated
        console.warn(`[background.js] Unknown closeDialogDefaultAction: ${userCloseDialogDefaultAction}. Defaulting to tray.`);
        if (mainWindow) {
          mainWindow.hide();
        }
      }
    }
  });

  // Listen for theme changes to update titleBarOverlay
  nativeTheme.on('updated', () => {
    if (mainWindow && !mainWindow.isDestroyed()) {
      // Send theme update to renderer so it can react if needed (e.g. for non-CSS theme parts)
      if (mainWindow && mainWindow.webContents) {
        mainWindow.webContents.send('native-theme-updated', nativeTheme.shouldUseDarkColors ? 'dark' : 'light');
      }
    }
  });
}

// --- IPC Handlers for Data Persistence ---
ipcMain.handle('load-app-data', async () => {
  try {
    // 配置从electron-store获取，待办事项数据从SQLite获取
    // 从electron-store获取设置
    console.log('[background.js] load-app-data: 尝试从electron-store获取配置');
    
    // 重要：每次获取时都从磁盘重新读取配置，确保获取最新设置
    // 这样避免了缓存问题导致数据不更新
    const storeSettings = store.get('settings');
    console.log('[background.js] load-app-data: 从electron-store获取的原始配置:', storeSettings);
    
    const settings = storeSettings || { 
      theme: 'dark', 
      miniMode: false, 
      alwaysOnTop: false, 
      showCloseDialog: true, 
      closeDialogDefaultAction: 'tray',
      launchOnStartup: false,
      sqlitePath: null
    };
    
    console.log('[background.js] load-app-data: 返回的最终配置:', settings);
    
    // 待办事项数据只从SQLite获取
    if (dbModule.checkConnection()) {
      console.log('[background.js] load-app-data: 从SQLite加载待办数据');
      try {
        const result = await dbModule.loadAllData();
        
        // 合并结果，用electron-store的设置覆盖SQLite的设置
        return { 
          ...result, 
          settings: settings 
        };
      } catch (dbError) {
        console.error('[background.js] 从SQLite加载待办数据失败:', dbError);
        // SQLite加载失败时返回空数据，但保留配置
        return { 
          todosByDate: {}, 
          inboxTodos: [], 
          archivedTodos: [], 
          settings: settings
        };
      }
    } else {
      // SQLite不可用，返回空数据
      console.error('[background.js] load-app-data: SQLite不可用，返回空待办数据');
      return { 
        todosByDate: {}, 
        inboxTodos: [], 
        archivedTodos: [], 
        settings: settings
      };
    }
  } catch (error) {
    console.error('[background.js] Error loading data:', error);
    // Return default structure on error to prevent renderer issues
    return { 
      todosByDate: {}, 
      inboxTodos: [], 
      archivedTodos: [], 
      settings: { 
        theme: 'dark', 
        miniMode: false, 
        alwaysOnTop: false, 
        showCloseDialog: true, 
        closeDialogDefaultAction: 'tray',
        launchOnStartup: false,
        sqlitePath: null
      }
    };
  }
});

ipcMain.on('save-app-data', (event, dataToSave) => {
  try {
    if (!dataToSave) return;
    
    // 设置始终保存到electron-store
    if (dataToSave.settings !== undefined) {
      store.set('settings', dataToSave.settings);
      console.log('[background.js] 配置已保存到electron-store');
    }
    
    // 待办事项数据只保存到SQLite
    if (dbModule.checkConnection()) {
      console.log('[background.js] save-app-data: 保存待办数据到SQLite');
      
      try {
        // 处理待办事项数据
        if (dataToSave.todosByDate) {
          // 这里简单记录，实际处理在db.js中完成
          console.log('[background.js] todosByDate已通过相应的SQLite API保存');
        }
        
        if (dataToSave.inboxTodos) {
          console.log('[background.js] inboxTodos已通过相应的SQLite API保存');
        }
        
        if (dataToSave.archivedTodos) {
          console.log('[background.js] archivedTodos已通过相应的SQLite API保存');
        }
      } catch (dbError) {
        console.error('[background.js] 保存待办数据到SQLite出错:', dbError);
      }
    } else {
      // SQLite不可用，显示错误提示，不保存到electron-store
      console.error('[background.js] SQLite不可用，无法保存待办数据');
      // 可能的话，通知用户数据保存失败
      if (mainWindow && !mainWindow.isDestroyed()) {
        mainWindow.webContents.send('db-save-error', {
          message: 'SQLite数据库连接失败，无法保存待办事项数据'
        });
      }
    }
  } catch (error) {
    console.error('[background.js] 保存数据出错:', error);
  }
});

// --- SQLite数据库 IPC处理程序 ---

// Handler for db-load-all-data
ipcMain.handle('db-load-all-data', async () => {
  console.log('[background.js] Received db-load-all-data request');
  if (!dbInitialized) {
    console.warn('[background.js] db-load-all-data: DB not initialized, returning undefined.');
    return undefined; 
  }
  try {
    const data = dbModule.loadAllData();
    console.log('[background.js] db-load-all-data: Loaded data from dbModule:', data ? JSON.parse(JSON.stringify(data)) : null);
    return data;
  } catch (error) {
    console.error('[background.js] db-load-all-data: Error loading data:', error);
    return undefined;
  }
});

// Handler for db-get-todos-by-date (retains existing full load functionality if needed elsewhere)
ipcMain.handle('db-get-todos-by-date', async () => {
  console.log('[background.js] Received db-get-todos-by-date request');
  if (!dbInitialized) return {};
  try {
    return dbModule.getTodosByDate();
  } catch (error) {
    console.error('[background.js] Error in db-get-todos-by-date:', error);
    return {};
  }
});

// 新增：Handler for db-get-todos-for-date-key
ipcMain.handle('db-get-todos-for-date-key', async (event, { dateKey }) => {
  console.log(`[background.js] Received db-get-todos-for-date-key request for date: ${dateKey}`);
  if (!dbInitialized) {
    console.warn('[background.js] db-get-todos-for-date-key: DB not initialized, returning empty array.');
    return [];
  }
  if (!dateKey) {
    console.error('[background.js] db-get-todos-for-date-key: dateKey is undefined or null.');
    return [];
  }
  try {
    const todos = dbModule.getTodosForDateKey(dateKey);
    console.log(`[background.js] db-get-todos-for-date-key: Loaded ${todos.length} todos for date ${dateKey}.`);
    return todos;
  } catch (error) {
    console.error(`[background.js] Error in db-get-todos-for-date-key for date ${dateKey}:`, error);
    return [];
  }
});

// Handler for db-get-inbox-todos
ipcMain.handle('db-get-inbox-todos', async () => {
  console.log('[background.js] Received db-get-inbox-todos request');
  if (!dbInitialized) return [];
  try {
    return dbModule.getInboxTodos();
  } catch (error) {
    console.error('[background.js] Error in db-get-inbox-todos:', error);
    return [];
  }
});

// Handler for db-get-archived-todos
ipcMain.handle('db-get-archived-todos', async () => {
  console.log('[background.js] Received db-get-archived-todos request');
  if (!dbInitialized) return [];
  try {
    return dbModule.getArchivedTodos();
  } catch (error) {
    console.error('[background.js] Error in db-get-archived-todos:', error);
    return [];
  }
});

// Handler for db-add-todo-to-date
ipcMain.handle('db-add-todo-to-date', async (event, { todo, dateKey }) => {
  console.log('[background.js] Received db-add-todo-to-date request');
  if (!dbInitialized) return false;
  try {
    return dbModule.addTodoToDate(todo, dateKey);
  } catch (error) {
    console.error('[background.js] Error in db-add-todo-to-date:', error);
    return false;
  }
});

// 待办事项操作
ipcMain.handle('db-add-todo', (event, { todo, source }) => {
  try {
    if (!dbModule.checkConnection()) {
      throw new Error('数据库未连接');
    }
    return dbModule.addTodo(todo, source);
  } catch (error) {
    console.error('[background.js] db-add-todo 出错:', error);
    return false;
  }
});

ipcMain.handle('db-update-todo', (event, { todo }) => {
  try {
    if (!dbModule.checkConnection()) {
      throw new Error('数据库未连接');
    }
    return dbModule.updateTodo(todo);
  } catch (error) {
    console.error('[background.js] db-update-todo 出错:', error);
    return false;
  }
});

ipcMain.handle('db-delete-todo', (event, { todoId }) => {
  try {
    if (!dbModule.checkConnection()) {
      throw new Error('数据库未连接');
    }
    return dbModule.deleteTodo(todoId);
  } catch (error) {
    console.error('[background.js] db-delete-todo 出错:', error);
    return false;
  }
});

// 按日期待办事项操作
ipcMain.handle('db-delete-todo-from-date', (event, { todoId, dateKey }) => {
  try {
    if (!dbModule.checkConnection()) {
      throw new Error('数据库未连接');
    }
    return dbModule.deleteTodoFromDate(todoId, dateKey);
  } catch (error) {
    console.error('[background.js] db-delete-todo-from-date 出错:', error);
    return false;
  }
});

ipcMain.handle('db-delete-batch-todos-from-date', (event, { todoIds, dateKey }) => {
  try {
    if (!dbModule.checkConnection()) {
      throw new Error('数据库未连接');
    }
    return dbModule.deleteBatchTodosFromDate(todoIds, dateKey);
  } catch (error) {
    console.error('[background.js] db-delete-batch-todos-from-date 出错:', error);
    return false;
  }
});

// 收件箱待办事项操作
ipcMain.handle('db-add-inbox-todo', (event, { todo }) => {
  try {
    if (!dbModule.checkConnection()) {
      throw new Error('数据库未连接');
    }
    return dbModule.addInboxTodo(todo);
  } catch (error) {
    console.error('[background.js] db-add-inbox-todo 出错:', error);
    return false;
  }
});

ipcMain.handle('db-delete-inbox-todo', (event, { todoId }) => {
  try {
    if (!dbModule.checkConnection()) {
      throw new Error('数据库未连接');
    }
    return dbModule.deleteInboxTodo(todoId);
  } catch (error) {
    console.error('[background.js] db-delete-inbox-todo 出错:', error);
    return false;
  }
});

// Handler for db-delete-batch-inbox-todos
ipcMain.handle('db-delete-batch-inbox-todos', async (event, { todoIdsArray }) => {
  console.log('[background.js] Received db-delete-batch-inbox-todos request');
  if (!dbInitialized) return false;
  try {
    return dbModule.deleteBatchInboxTodos(todoIdsArray);
  } catch (error) {
    console.error('[background.js] Error in db-delete-batch-inbox-todos:', error);
    return false;
  }
});

// 归档待办事项操作
ipcMain.handle('db-archive-todo', (event, { todo, originalSource }) => {
  try {
    if (!dbModule.checkConnection()) {
      throw new Error('数据库未连接');
    }
    return dbModule.archiveTodo(todo, originalSource);
  } catch (error) {
    console.error('[background.js] db-archive-todo 出错:', error);
    return false;
  }
});

ipcMain.handle('db-archive-batch-todos', (event, { todos, source }) => {
  try {
    if (!dbModule.checkConnection()) {
      throw new Error('数据库未连接');
    }
    return dbModule.archiveBatchTodos(todos, source);
  } catch (error) {
    console.error('[background.js] db-archive-batch-todos 出错:', error);
    return false;
  }
});

ipcMain.handle('db-delete-archived-todo', (event, { todoId }) => {
  try {
    if (!dbModule.checkConnection()) {
      throw new Error('数据库未连接');
    }
    return dbModule.deleteArchivedTodo(todoId);
  } catch (error) {
    console.error('[background.js] db-delete-archived-todo 出错:', error);
    return false;
  }
});

ipcMain.handle('db-delete-archived-batch-todos', (event, { todoIds }) => {
  try {
    if (!dbModule.checkConnection()) {
      throw new Error('数据库未连接');
    }
    return dbModule.deleteArchivedBatchTodos(todoIds);
  } catch (error) {
    console.error('[background.js] db-delete-archived-batch-todos 出错:', error);
    return false;
  }
});

// 其他待办事项操作
ipcMain.handle('db-move-todo-to-date', (event, { todoId, newDateKey }) => {
  try {
    if (!dbModule.checkConnection()) {
      throw new Error('数据库未连接');
    }
    return dbModule.moveTodoToDate(todoId, newDateKey);
  } catch (error) {
    console.error('[background.js] db-move-todo-to-date 出错:', error);
    return false;
  }
});

// 设置操作
ipcMain.handle('db-get-settings', () => {
  try {
    if (!dbModule.checkConnection()) {
      throw new Error('数据库未连接');
    }
    return dbModule.getSettings();
  } catch (error) {
    console.error('[background.js] db-get-settings 出错:', error);
    return null;
  }
});

ipcMain.handle('db-update-settings', (event, { settings }) => {
  try {
    if (!dbModule.checkConnection()) {
      throw new Error('数据库未连接');
    }
    return dbModule.updateSettings(settings);
  } catch (error) {
    console.error('[background.js] db-update-settings 出错:', error);
    return false;
  }
});

// 数据迁移
ipcMain.handle('db-migrate-from-store', () => {
  try {
    if (!dbModule.checkConnection()) {
      throw new Error('数据库未连接');
    }
    
    // 从electron-store获取数据
    const data = {
      todosByDate: store.get('todosByDate', {}),
      inboxTodos: store.get('inboxTodos', []),
      archivedTodos: store.get('archivedTodos', []),
      settings: store.get('settings', {})
    };
    
    // 迁移数据到SQLite
    const migrationResult = dbModule.migrateFromElectronStore(data);
    
    // 如果迁移成功，可以清空electron-store（可选）
    // if (migrationResult) {
    //   store.clear();
    // }
    
    return migrationResult;
  } catch (error) {
    console.error('[background.js] db-migrate-from-store 出错:', error);
    return false;
  }
});

// 在应用关闭时关闭数据库连接
app.on('before-quit', () => {
  console.log('[background.js] 应用关闭前，关闭数据库连接');
  dbModule.closeDatabase();
});

// --- Other IPC Handlers (as before or new ones) ---
ipcMain.handle('get-initial-maximize-status', async () => {
  if (mainWindow) {
    return mainWindow.isMaximized();
  }
  return false;
});

// Example: Toggle Mini Mode IPC from renderer
ipcMain.on('toggle-mini-mode-visuals', (event, isMini) => {
  console.log(`[background.js] Received 'toggle-mini-mode-visuals' from renderer with isMini: ${isMini}`);
  performToggleMiniMode(isMini);
});

// New handler for the custom title bar's close button
ipcMain.on('initiate-window-close', () => {
  if (mainWindow) {
    console.log("[background.js] 'initiate-window-close' IPC received. Calling mainWindow.close().");
    mainWindow.close(); // This will trigger the mainWindow.on('close', ...) logic
  }
});

ipcMain.on('set-force-quit', () => {
  console.log("[background.js] set-force-quit received. App will close without prompt.");
  forceQuit = true;
  app.quit();
});

ipcMain.on('open-dev-tools', () => {
  if (mainWindow && mainWindow.webContents) {
    mainWindow.webContents.openDevTools();
  }
});

ipcMain.on('minimize-window', () => {
  if (mainWindow) mainWindow.minimize();
});

ipcMain.on('maximize-unmaximize-window', () => {
  if (mainWindow) {
    if (mainWindow.isMaximized()) {
      mainWindow.unmaximize();
    } else {
      mainWindow.maximize();
    }
  }
});

ipcMain.on('close-window', () => { // This will trigger the 'close' event on mainWindow
  if (mainWindow) {
    console.log("[background.js] 'close-window' IPC received. Closing main window.");
    // mainWindow.close(); // OLD HANDLER - Commented out or to be removed
    // This channel might be deprecated or needs re-evaluation if it's still used elsewhere.
    // For now, we assume 'initiate-window-close' is the new primary way for renderer to request a standard close.
    console.warn("[background.js] 'close-window' IPC channel was called, but it might be deprecated. Consider using 'initiate-window-close'. For safety, this call will now also trigger a standard close.");
    if (mainWindow) {
        mainWindow.close();
    }
}
});


// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  console.log('[background.js] App is ready.');

  // Initialize DB here, before creating window and before notification check
  // dbPath is defined globally from the earlier logic
  if (typeof dbPath === 'undefined') {
    console.error('[background.js] CRITICAL: dbPath is undefined in app.on("ready"). Halting DB initialization.');
    // dbInitialized remains false
  } else {
    console.log(`[background.js] 开始初始化数据库 (in ready): ${dbPath}`);
    try {
      const initResult = dbModule.initDatabase(dbPath);
      dbInitialized = initResult; // Set the global dbInitialized
      console.log(`[background.js] SQLite数据库初始化 (in ready) ${dbInitialized ? '成功' : '失败'}`);
      if (!dbInitialized) {
        console.log('[background.js] 由于SQLite数据库初始化失败 (in ready)，后续可能使用electron-store');
      }
    } catch (initError) {
        console.error('[background.js] 数据库初始化时发生错误 (in ready):', initError);
        dbInitialized = false; // Ensure it's false on error
    }
  }

  createWindow();

  // Create Tray Icon
  let iconName = 'app-icon.ico'; // 修改成与窗口相同的图标文件名
  let iconPath;
  if (isDevelopment) {
    // 开发模式下，图标通常在 public 文件夹中，相对于项目根目录
    iconPath = nodePath.join(process.cwd(), 'public', iconName);
    // 检查文件是否存在，如果不存在尝试其他路径
    if (!fs.existsSync(iconPath)) {
        iconPath = nodePath.join(app.getAppPath(), 'public', iconName);
    }
    if (!fs.existsSync(iconPath)) {
        iconPath = nodePath.join(app.getAppPath(), '../public', iconName);
    }
    // 再次检查，如果还找不到，记录错误
    if (!fs.existsSync(iconPath)) {
        console.error(`[background.js] Tray icon not found in dev at: ${iconPath}. Please check path.`);
    }
  } else {
    // 生产模式下，图标应该在打包的应用资源目录
    iconPath = nodePath.join(process.resourcesPath, iconName);
    if (!fs.existsSync(iconPath)) {
        iconPath = nodePath.join(app.getAppPath(), iconName);
    }
    if (!fs.existsSync(iconPath)) {
        console.error(`[background.js] Tray icon not found in prod at: ${iconPath}. Ensure it's in 'extraResources' or copied by builder.`);
    }
  }
  console.log(`[background.js] Attempting to load tray icon from: ${iconPath}`);

  // 只有当 iconPath 有效或者我们有一个默认图标时才创建 Tray
  if (fs.existsSync(iconPath)) {
    tray = new Tray(iconPath);
    const contextMenu = Menu.buildFromTemplate([
      {
        label: '显示/隐藏应用',
        click: () => {
          if (mainWindow) {
            if (mainWindow.isVisible() && !mainWindow.isMinimized()) {
              mainWindow.hide();
            } else {
              mainWindow.show();
              mainWindow.focus(); // 确保窗口获得焦点
            }
          }
        }
      },
      {
        label: '重启应用',
        click: () => {
          console.log('[background.js] Tray menu: Restarting app with --show-on-restart');
          // 确保从原始参数开始，并移除可能冲突的 --launch-in-tray
          const args = process.argv.slice(1).filter(arg => arg !== '--launch-in-tray');
          // 添加 --show-on-restart 确保重启后窗口显示
          if (!args.includes('--show-on-restart')) {
            args.push('--show-on-restart');
          }
          // 设置标记，以便重启逻辑可以强制显示窗口
          store.set('restart_show_window', true);
          app.relaunch({ args: args });
          // 短暂延迟后退出，确保relaunch命令有足够时间启动
          setTimeout(() => app.exit(0), 500); 
        }
      },
      { type: 'separator' }, // Separator
      {
        label: '退出',
        click: () => {
          forceQuit = true;
          app.quit();
        }
      }
    ]);

    tray.setToolTip('待办事项'); // 使用您的产品名称
    tray.setContextMenu(contextMenu);

    tray.on('click', () => {
      if (mainWindow) {
        if (mainWindow.isVisible() && !mainWindow.isMinimized()) {
          // 如果窗口可见且未最小化，则隐藏
          mainWindow.hide();
        } else {
          // 如果窗口不可见或已最小化，则显示并获取焦点
          mainWindow.show();
          mainWindow.focus();
        }
      }
    });
    console.log("[background.js] System tray icon created successfully.");
  } else {
    console.error("[background.js] Could not create system tray icon because icon file was not found at the determined path:", iconPath);
  }

  // 从electron-store获取应用设置
  console.log('[background.js] 从electron-store获取应用设置');
  const initialSettings = store.get('settings');
  let launchOnStartup = false;
  
  // 只有当settings存在并且包含launchOnStartup属性时才使用该值
  if (initialSettings && typeof initialSettings.launchOnStartup === 'boolean') {
    launchOnStartup = initialSettings.launchOnStartup;
  }

  // 应用启动设置
  applyLoginItemSettings(launchOnStartup);

  // 如果配置文件是新创建的（不存在），会通过schema设置默认值，无需额外操作
  // 如果配置文件已存在但没有launchOnStartup属性，添加该属性
  if (initialSettings && typeof initialSettings.launchOnStartup === 'undefined') {
    console.log('[background.js] 现有配置中未找到launchOnStartup设置，添加默认值false');
    
    // 更新electron-store，保留现有配置，只添加缺少的属性
    store.set('settings', { ...initialSettings, launchOnStartup: false });
    console.log('[background.js] 在electron-store中添加launchOnStartup=false');
  }

  // Notify user about today's todos after app is ready
  try {
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed
    const day = String(today.getDate()).padStart(2, '0');
    const todayDateString = `${year}-${month}-${day}`;

    let todaysTodos = [];
    let numberOfTodaysTodos = 0;
    
    // 首先尝试从SQLite数据库获取
    // Use the dbInitialized set within app.on('ready')
    if (dbInitialized && dbModule.checkConnection()) {
      console.log(`[background.js] 尝试从SQLite获取今日(${todayDateString})待办事项 (after in-ready init)`);
      try {
        const todosByDate = dbModule.getTodosByDate();
        todaysTodos = todosByDate[todayDateString] || [];
        numberOfTodaysTodos = todaysTodos.length;
        console.log(`[background.js] 从SQLite找到${numberOfTodaysTodos}条今日待办事项 (after in-ready init)`);
      } catch (dbError) {
        console.error('[background.js] 从SQLite获取今日待办事项失败 (after in-ready init):', dbError);
        // 回退到electron-store
    const allTodosByDate = store.get('todosByDate', {});
        todaysTodos = allTodosByDate[todayDateString] || [];
        numberOfTodaysTodos = todaysTodos.length;
        console.log(`[background.js] 从electron-store找到${numberOfTodaysTodos}条今日待办事项 (SQLite read error fallback)`);
      }
    } else {
      // SQLite未初始化或连接失败，使用electron-store
      if (!dbInitialized) {
        console.log(`[background.js] SQLite未初始化成功 (in ready)，从electron-store获取今日待办事项`);
      } else { // dbInitialized is true but checkConnection is false
         console.log(`[background.js] SQLite初始化但连接失败，从electron-store获取今日待办事项`);
      }
      const allTodosByDate = store.get('todosByDate', {});
      todaysTodos = allTodosByDate[todayDateString] || [];
      numberOfTodaysTodos = todaysTodos.length;
      console.log(`[background.js] 从electron-store找到${numberOfTodaysTodos}条今日待办事项 (direct fallback)`);
    }

    console.log(`[background.js] 今日待办事项检查(${todayDateString})结果: ${numberOfTodaysTodos}条`);

    if (numberOfTodaysTodos > 0) {
      if (Notification.isSupported()) {
        const notification = new Notification({
          title: '今日待办提醒',
          body: `您今天有 ${numberOfTodaysTodos} 条待办事项。`,
          // icon: nodePath.join(__dirname, 'path/to/your/app/icon.png'), // Optional: specify an icon
          silent: false
        });
        notification.show();
        console.log(`[background.js] 已发送今日${numberOfTodaysTodos}条待办事项的通知`);
      } else {
        console.log('[background.js] 系统不支持通知功能，无法发送今日待办提醒');
      }
    }
  } catch (error) {
    console.error('[background.js] 检查或通知今日待办事项时出错:', error);
  }

  // 启动提醒检查
  startReminderCheck();
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}

// Add a handler for uncaught exceptions in the main process
process.on('uncaughtException', (error) => {
  console.error('Uncaught Exception in main process:', error);
  // Optionally, inform the user via a dialog
  if (mainWindow && !mainWindow.isDestroyed()) {
    dialog.showErrorBox('Application Error', 'An unexpected error occurred. Please restart the application.');
  }
  // It's often recommended to quit the app after an uncaught exception in main
  // app.quit(); // Consider the implications before enabling this
});

// Example IPC handler (you might have others)
ipcMain.on('some-existing-ipc-channel', (event, arg) => {
  // console.log(arg); 
  // event.reply('some-existing-ipc-channel-reply', 'pong');
});

// IPC Handler for showing Pomodoro notifications
ipcMain.on('show-pomodoro-notification', (event, { title, body }) => {
  if (Notification.isSupported()) {
    const notification = new Notification({
      title: title, // Use the title directly, even if it's an empty string
      body: body || '一个时段已结束。',
      // icon: nodePath.join(__dirname, 'path/to/icon.png'), // Optional: add an icon
      silent: false // Set to true if you want silent notifications initially
    });
    notification.show();
  } else {
    console.log('系统通知在本平台上不受支持。');
  }
});

// IPC Handler to open directory selection dialog
ipcMain.handle('select-data-directory', async () => {
  if (!mainWindow) {
    return { error: 'Main window not available' };
  }
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openDirectory']
  });
  if (result.canceled || result.filePaths.length === 0) {
    return { path: null }; // User cancelled or selected nothing
  }
  return { path: result.filePaths[0] };
});

// Helper function to move data and re-initialize store (simplified version)
async function moveDataAndNotify(newDirectoryPath) {
  const oldStorePath = store.path;
  const oldDirectory = nodePath.dirname(oldStorePath);
  const newConfigPath = nodePath.join(newDirectoryPath, 'config.json');
  const oldDbPath = dbPath;
  const newDbPath = nodePath.join(newDirectoryPath, 'todolist.db');

  console.log(`[background.js] Attempting to move data. Old store path: ${oldStorePath}, Old DB path: ${oldDbPath}, New target directory: ${newDirectoryPath}`);

  // Basic check: Don't move if source and target directory are essentially the same
  // This check might need to be more robust depending on how paths are normalized
  if (oldDirectory === newDirectoryPath) {
    console.log('[background.js] Old and new directory are the same. No move needed. Updating pathStore.');
    pathStore.set('customDataPath', newDirectoryPath);
    // Even if no move, tell renderer to prompt for restart as store path might be interpreted differently on next launch
    if (mainWindow && mainWindow.webContents) {
      mainWindow.webContents.send('data-path-changed-restart-required');
    }
    return { success: true, message: 'Path updated. Restart recommended.' };
  }

  try {
    // 1. Ensure new directory exists
    await fs.ensureDir(newDirectoryPath);
    console.log(`[background.js] Ensured new directory exists: ${newDirectoryPath}`);

    // 2. Check if the old config.json exists
    if (fs.existsSync(oldStorePath)) {
      // 3. Move the config.json file
      await fs.move(oldStorePath, newConfigPath, { overwrite: true });
      console.log(`[background.js] Successfully moved ${oldStorePath} to ${newConfigPath}`);
    } else {
      console.warn(`[background.js] Old config file ${oldStorePath} not found. Only updating path reference.`);
    }
    
    // 4. 如果存在SQLite数据库文件，也一并移动
    if (fs.existsSync(oldDbPath)) {
      await fs.move(oldDbPath, newDbPath, { overwrite: true });
      console.log(`[background.js] Successfully moved SQLite database from ${oldDbPath} to ${newDbPath}`);
    } else {
      console.warn(`[background.js] Old SQLite database file ${oldDbPath} not found. It will be created at the new location on next launch.`);
    }

    // 5. Update the pathStore with the new directory path
    pathStore.set('customDataPath', newDirectoryPath);
    console.log(`[background.js] Custom data path updated in pathStore: ${newDirectoryPath}`);

    // 6. Inform renderer that a restart is needed
    if (mainWindow && mainWindow.webContents) {
      mainWindow.webContents.send('data-path-changed-restart-required');
    }

    return { success: true, message: 'Data path updated. Please restart the application.' };

  } catch (error) {
    console.error('[background.js] Error moving data or updating path:', error);
    // Attempt to revert pathStore change if move failed significantly
    return { success: false, error: `Failed to move data: ${error.message}` };
  }
}

// IPC Handler to set new data path
ipcMain.handle('set-custom-data-path', async (event, newPath) => {
  if (!newPath || typeof newPath !== 'string') {
    return { success: false, error: 'Invalid path provided.' };
  }
  console.log(`[background.js] Received request to set custom data path to: ${newPath}`);
  // It's crucial that the main `store` object is not re-instantiated here directly
  // as it would lose its current in-memory state. The data move happens,
  // and the new path is saved. The app MUST be restarted for the main `store`
  // to pick up the new `cwd` from `pathStore` on its next initialization.
  return await moveDataAndNotify(newPath);
});

// 添加新的IPC处理程序：设置SQLite数据库路径
ipcMain.handle('set-sqlite-db-path', async (event, newPath) => {
  try {
    if (!newPath || typeof newPath !== 'string') {
      return { success: false, error: '无效的路径' };
    }
    
    console.log(`[background.js] 收到设置SQLite数据库路径请求: ${newPath}`);
    
    // 验证目录是否可用
    try {
      const sqliteDir = nodePath.dirname(newPath);
      fs.ensureDirSync(sqliteDir);
      
      // 尝试写入测试文件确认权限
      const testFilePath = nodePath.join(sqliteDir, 'test_write_access.tmp');
      fs.writeFileSync(testFilePath, 'test');
      fs.unlinkSync(testFilePath);
    } catch (err) {
      console.error(`[background.js] 无法访问或写入目录: ${nodePath.dirname(newPath)}`, err);
      return { success: false, error: `无法访问或写入目录: ${err.message}` };
    }
    
    // 保存路径到配置
    const currentSettings = store.get('settings', {});
    store.set('settings', { ...currentSettings, sqlitePath: newPath });
    console.log(`[background.js] SQLite数据库路径已保存到配置: ${newPath}`);
    
    // 关闭现有数据库连接
    if (dbModule) {
      try {
        dbModule.closeDatabase();
        console.log('[background.js] 已关闭现有SQLite数据库连接');
      } catch (closeErr) {
        console.warn('[background.js] 关闭数据库连接时出现警告:', closeErr);
        // 继续执行，不影响路径更新
      }
    }
    
    // 检查数据库文件是否存在，如果不存在则创建
    const dbFileExists = fs.existsSync(newPath);
    if (!dbFileExists) {
      console.log(`[background.js] SQLite数据库文件不存在，正在创建: ${newPath}`);
      
      try {
        // 加载better-sqlite3模块
        let Database = null;
        try {
          Database = require('better-sqlite3');
        } catch (err) {
          console.error('[background.js] 加载better-sqlite3模块失败:', err.message);
          return { 
            success: true, 
            message: 'SQLite数据库路径已更新，但无法创建数据库文件。请重启应用后系统将自动创建。',
            needRestart: true
          };
        }
        
        // 创建新的数据库连接
        const newDb = new Database(newPath, { verbose: console.log });
        
        // 创建必要的表结构
        newDb.exec(`
          CREATE TABLE IF NOT EXISTS todos (
            id TEXT PRIMARY KEY,
            text TEXT NOT NULL,
            completed INTEGER NOT NULL DEFAULT 0,
            created_at TEXT NOT NULL,
            completed_date TEXT,
            priority INTEGER NOT NULL DEFAULT 0,
            date_key TEXT,
            source TEXT NOT NULL DEFAULT 'inbox',
            archived INTEGER NOT NULL DEFAULT 0,
            archived_date TEXT,
            original_source TEXT
          );
        `);
        
        // 关闭连接
        newDb.close();
        console.log(`[background.js] 已成功创建SQLite数据库文件: ${newPath}`);
      } catch (createErr) {
        console.error(`[background.js] 创建SQLite数据库文件失败:`, createErr);
        // 即使创建失败，仍然返回成功状态，因为路径已保存，重启后系统会尝试创建
        return { 
          success: true, 
          message: 'SQLite数据库路径已更新，但创建数据库文件失败。请重启应用后系统将尝试重新创建。',
          needRestart: true
        };
      }
    }
    
    // 通知渲染进程需要重启
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.webContents.send('sqlite-path-changed-restart-required');
    }
    
    return { 
      success: true, 
      message: 'SQLite数据库路径已更新，请重启应用以应用更改', 
      dbCreated: !dbFileExists,
      needRestart: true
    };
  } catch (error) {
    console.error('[background.js] 设置SQLite数据库路径出错:', error);
    return { success: false, error: error.message || '未知错误' };
  }
});

// 添加IPC处理程序：选择SQLite数据库路径
ipcMain.handle('select-sqlite-db-path', async () => {
  if (!mainWindow) {
    return { error: 'Main window not available' };
  }
  
  try {
    const result = await dialog.showOpenDialog(mainWindow, {
      title: '选择SQLite数据库路径',
      defaultPath: nodePath.dirname(dbPath),
      buttonLabel: '选择此文件夹',
      properties: ['openDirectory']
    });
    
    if (result.canceled || result.filePaths.length === 0) {
      return { path: null }; // 用户取消或未选择
    }
    
    let selectedPath = result.filePaths[0];
    // 如果只选择了文件夹，则添加默认文件名
    if (!selectedPath.endsWith('.db')) {
      selectedPath = nodePath.join(selectedPath, 'todolist.db');
    }
    
    return { path: selectedPath };
  } catch (error) {
    console.error('[background.js] 选择SQLite数据库路径出错:', error);
    return { error: error.message || '选择文件夹时发生错误' };
  }
});

// 添加IPC处理程序：重启应用程序
ipcMain.on('restart-app', (event, options = {}) => {
  console.log('[background.js] 接收到重启应用程序请求', options);
  
  // 添加启动参数以确保重启后显示主窗口
  let args = process.argv.slice(1).filter(arg => arg !== '--launch-in-tray');
  
  // 获取选项中的showMainWindow参数
  if (options && options.showMainWindow === true) {
    // 确保添加显示主窗口的参数，并移除可能存在的相反参数
    if (!args.includes('--show-on-restart')) {
      args.push('--show-on-restart');
    }
    console.log('[background.js] 已添加--show-on-restart参数以确保重启后显示主窗口');
    
    // 在store中保存一个标志，表示重启后应该显示主窗口
    try {
      store.set('restart_show_window', true);
      console.log('[background.js] 已在配置中设置重启显示窗口标志');
    } catch (storeError) {
      console.error('[background.js] 保存重启设置到store失败:', storeError);
    }
  }
  
  console.log('[background.js] 重启应用程序，参数:', args);
  
  try {
    // 确保所有数据都已保存
    console.log('[background.js] 配置已保存到electron-store');
    
    // 使用app.relaunch和app.exit组合确保应用程序重启
    app.relaunch({ args });
    
    // 短暂延迟后退出应用，确保数据已保存
    setTimeout(() => {
      try {
        app.exit(0);
      } catch (exitError) {
        console.error('[background.js] app.exit(0)执行出错:', exitError);
        app.quit();
      }
    }, 500); // 增加延迟时间确保资源释放和数据保存
  } catch (err) {
    console.error('[background.js] 重启应用程序出错:', err);
    if (mainWindow && !mainWindow.isDestroyed()) {
      dialog.showErrorBox('重启失败', '应用程序重启失败，请手动关闭并重新打开应用。');
    }
  }
});

// --- 提醒功能相关的IPC处理程序 ---
ipcMain.handle('db-get-all-reminders', async () => {
  console.log('[background.js] 收到获取所有提醒请求');
  if (!dbInitialized) {
    console.warn('[background.js] db-get-all-reminders: 数据库未初始化，返回空数组');
    return [];
  }
  try {
    const reminders = dbModule.getAllReminders();
    console.log(`[background.js] 成功获取${reminders.length}条提醒`);
    return reminders;
  } catch (error) {
    console.error('[background.js] 获取提醒列表时出错:', error);
    return [];
  }
});

ipcMain.handle('db-create-reminder', async (event, { reminder }) => {
  console.log('[background.js] 收到创建提醒请求');
  if (!dbInitialized) {
    console.warn('[background.js] db-create-reminder: 数据库未初始化');
    return { success: false, error: '数据库未初始化' };
  }
  try {
    const result = dbModule.createReminder(reminder);
    console.log('[background.js] 提醒创建结果:', result);
    return { success: !!result, reminder: result };
  } catch (error) {
    console.error('[background.js] 创建提醒时出错:', error);
    return { success: false, error: error.message };
  }
});

ipcMain.handle('db-update-reminder', async (event, { reminder }) => {
  console.log('[background.js] 收到更新提醒请求');
  if (!dbInitialized) {
    console.warn('[background.js] db-update-reminder: 数据库未初始化');
    return { success: false, error: '数据库未初始化' };
  }
  try {
    const result = dbModule.updateReminder(reminder);
    console.log('[background.js] 提醒更新结果:', result);
    return { success: !!result, reminder: result };
  } catch (error) {
    console.error('[background.js] 更新提醒时出错:', error);
    return { success: false, error: error.message };
  }
});

ipcMain.handle('db-delete-reminder', async (event, { reminderId }) => {
  console.log('[background.js] 收到删除提醒请求');
  if (!dbInitialized) {
    console.warn('[background.js] db-delete-reminder: 数据库未初始化');
    return { success: false, error: '数据库未初始化' };
  }
  try {
    const result = dbModule.deleteReminder(reminderId);
    console.log('[background.js] 提醒删除结果:', result);
    return { success: !!result };
  } catch (error) {
    console.error('[background.js] 删除提醒时出错:', error);
    return { success: false, error: error.message };
  }
});

ipcMain.handle('db-update-reminder-active', async (event, { reminderId, isActive }) => {
  console.log('[background.js] 收到更新提醒状态请求');
  if (!dbInitialized) {
    console.warn('[background.js] db-update-reminder-active: 数据库未初始化');
    return { success: false, error: '数据库未初始化' };
  }
  try {
    // 将isActive转换为数字，SQLite中1表示true，0表示false
    const activeValue = isActive ? 1 : 0;
    const result = dbModule.updateReminderNextTrigger(reminderId, null, activeValue);
    console.log('[background.js] 提醒状态更新结果:', result);
    return { success: !!result };
  } catch (error) {
    console.error('[background.js] 更新提醒状态时出错:', error);
    return { success: false, error: error.message };
  }
});

// 定期检查到期提醒
let reminderCheckInterval = null;

function startReminderCheck() {
  // 每分钟检查一次
  reminderCheckInterval = setInterval(async () => {
    if (!dbInitialized) return;
    
    try {
      const currentTime = Date.now();
      const dueReminders = dbModule.getDueReminders(currentTime);
      
      if (dueReminders && dueReminders.length > 0) {
        console.log(`[background.js] 发现${dueReminders.length}条到期提醒`);
        
        // 处理每条到期提醒
        for (const reminder of dueReminders) {
          // 发送系统通知
          if (Notification.isSupported()) {
            const notification = new Notification({
              title: reminder.title,
              body: reminder.description || '定时提醒',
              silent: false
            });
            notification.show();
            
            // 点击通知时显示主窗口
            notification.on('click', () => {
              if (mainWindow) {
                if (mainWindow.isMinimized()) mainWindow.restore();
                if (!mainWindow.isVisible()) mainWindow.show();
                mainWindow.focus();
                // 导航到提醒页面
                mainWindow.webContents.send('navigate-to-reminder');
              }
            });
          }
          
          // 计算下一次触发时间并更新
          if (reminder.recurrenceType !== 'ONCE') {
            const nextTrigger = dbModule.calculateNextTriggerAfter(currentTime, reminder);
            if (nextTrigger) {
              dbModule.updateReminderNextTrigger(reminder.id, nextTrigger, reminder.isActive);
              console.log(`[background.js] 更新提醒 ${reminder.id} 的下一次触发时间为 ${new Date(nextTrigger).toLocaleString()}`);
            }
          } else {
            // 单次提醒，设置为非活跃
            dbModule.updateReminderNextTrigger(reminder.id, null, 0);
            console.log(`[background.js] 单次提醒 ${reminder.id} 已完成，设置为非活跃状态`);
          }
        }
      }
    } catch (error) {
      console.error('[background.js] 检查提醒时出错:', error);
    }
  }, 60000); // 60秒检查一次
  
  console.log('[background.js] 提醒检查定时器已启动');
}

// 在app.on('before-quit')中清除提醒检查定时器
app.on('before-quit', () => {
  // ... existing code ...
  
  // 清除提醒检查定时器
  if (reminderCheckInterval) {
    clearInterval(reminderCheckInterval);
    console.log('[background.js] 提醒检查定时器已清除');
  }
});

// 添加导航到提醒页面的IPC处理
ipcMain.on('navigate-to-reminder', () => {
  if (mainWindow && !mainWindow.isDestroyed()) {
    mainWindow.webContents.send('navigate-to-reminder');
  }
});

// Listen for theme changes to update titleBarOverlay
nativeTheme.on('updated', () => {
  if (mainWindow && !mainWindow.isDestroyed()) {
    // Send theme update to renderer so it can react if needed (e.g. for non-CSS theme parts)
    if (mainWindow && mainWindow.webContents) {
      mainWindow.webContents.send('native-theme-updated', nativeTheme.shouldUseDarkColors ? 'dark' : 'light');
    }
  }
});

// IPC handler for response from custom close dialog in renderer
ipcMain.on('custom-close-response', (event, choice, dontAskAgain) => {
  console.log(`[background.js] Received custom-close-response: choice=${choice}, dontAskAgain=${dontAskAgain}`);
  
  if (dontAskAgain) {
    console.log('[background.js] User chose "dontAskAgain". Updating settings.');
    
    // 只保存设置到electron-store
    const currentSettings = store.get('settings', {});
    const newSettings = {
      ...currentSettings,
      showCloseDialog: false,
      closeDialogDefaultAction: (choice === 'tray' || choice === 'close') ? choice : currentSettings.closeDialogDefaultAction || 'tray'
    };
    store.set('settings', newSettings);
    console.log('[background.js] 已保存关闭对话框设置到electron-store:', JSON.stringify({
      showCloseDialog: newSettings.showCloseDialog,
      closeDialogDefaultAction: newSettings.closeDialogDefaultAction
    }));
  }

  if (choice === 'tray') {
    console.log('[background.js] Minimizing to tray based on dialog choice.');
    if (mainWindow) {
      mainWindow.hide();
    }
  } else if (choice === 'close') {
    console.log('[background.js] Closing app based on dialog choice. Setting forceQuit and calling app.quit().');
    forceQuit = true; // Explicitly set forceQuit to true
    app.quit();
  } else if (choice === 'cancel') {
    console.log('[background.js] Close action cancelled by user.');
    // Do nothing, dialog is already hidden by renderer
  }
});